package com.ymh.git.thread.juc.threadpool;

import com.ymh.git.thread.juc.SleepTools;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by aivin on 2018/11/7.
 * 线程池的使用范例
 */
public class UseThreadPool {


    static class Worker implements Runnable {

        private String taskName;
        private Random random = new Random();

        public Worker(String taskName) {
            this.taskName = taskName;
        }

        public String getTaskName() {
            return taskName;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " process  the task: " + taskName);
            SleepTools.ms(random.nextInt(100) * 5);
        }
    }

    public static void main(String[] args) {
        ExecutorService pool = new ThreadPoolExecutor(2, 4, 3,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i <= 6; i++) {
            Worker worker = new Worker("worker" + i);
            System.out.println("A task has been added:" + worker.getTaskName());
            pool.execute(worker);
        }
        pool.shutdown();
    }
}
